<template>
  <view class="uploadingImg">
    <!-- 图片列表 -->
    <view v-for="(item, idx) in appends" :key="idx">
      <view class="img_warpBox">
        <view class="img_warp">
          <img v-if="item.url && item.type == 'img'" :src="item.src" class="img" />
          <view v-else class="fileBox">
            <img :src="getFileIcon(item.url)" class="fileImgStyle" />
          </view>
          <u-icon name="close-circle-fill" class="tc-theme det" @tap.stop="removeAppendix(idx)" />
        </view>
        <view class="nameStyle">{{item.name}}</view>
      </view>
    </view>
    <!-- 添加区域 -->
    <view v-if="showPlus" class="uploading_add" @tap="showMenu()">
      <u-icon name="plus" class="tc-theme fs24" />
    </view>
    <popup-wrapper ref="popup" type="bottom" width="100%" height="auto" transition="slider">
      <view class="userinfo-appendix-menu-wrapper">
        <view class="userinfo-appendix-menu">
          <view class="userinfo-appendix-menu-item" @tap="chooseImage">
            <img src="../images/bendi.png" lazy-load />
            <span>本地照片</span>
          </view>
          <view class="userinfo-appendix-menu-item" @tap="chooseFile">
            <img src="../images/weixin.png" />
            <span>微信文件</span>
          </view>
        </view>
        <view class="userinfo-appendix-menu-cancel" @tap="hideMenu">取消</view>
      </view>
    </popup-wrapper>

    <u-mask :show="mask" />
    <u-modal v-model="show" show-cancel-button :confirmColor="settings.theme" content="是否删除？" title="删除" @confirm="confirm" />
  </view>
</template>
<script>
import PopupWrapper from "@/components/lu-popup-wrapper/lu-popup-wrapper";
import {
  uploadSiteFile,
  uploadFileFormData,
  uploadImg,
  downloadFile
} from "@/services/common";
import { mapState } from "vuex";
const defaultAppend = {
  src: null,
  url: null, // 上传返回的地址
  name: null, // 如果是文件，显示文件名称
  type: null
};
const imgTypes = [
  "bmp",
  "jpg",
  "png",
  "tif",
  "gif",
  "pcx",
  "tga",
  "exif",
  "fpx",
  "svg",
  "psd",
  "cdr",
  "pcd",
  "dxf",
  "ufo",
  "eps",
  "ai",
  "raw",
  "WMF",
  "webp",
  "jpeg"
];
export default {
  name: "Appendix",
  components: {
    PopupWrapper
  },
  props: {
    maxCount: {
      type: Number,
      default: 8
    },
    label: {
      type: String,
      default: ""
    },
    value: {
      type: String,
      default: ""
    },
    count: {
      type: Number,
      default: 1
    },
    limit: {
      type: Number,
      default: 1
    },
    disabled: {
      type: Boolean,
      default: false
    },
    extra: {
      type: Boolean,
      default: true
    },
    type: {
      type: String,
      default: "uploadImg"
    }
  },
  data() {
    return {
      ingIndex: null,
      show: false,
      mask: false,
      ingNum: 0,
      appends: [],
      currentIdx: null
    };
  },
  computed: {
    ...mapState(["settings"]),
    isShow() {
      return this.value;
    },
    fileUrls: function() {
      return this.appends
        .filter(item => !!item.url)
        .map(item => item.url)
        .join(",");
    },
    showPlus: function() {
      console.log(" this.maxCount", this.maxCount);
      if (this.appends.length > this.maxCount) {
        return false;
      } else {
        return true;
      }
    }
  },
  watch: {
    isShow(newV, oldV) {
      this.initAppendix(newV);
    }
  },
  methods: {
    getFileIcon(src) {
      let val = src
        .split("/")
        .slice(-1)[0]
        .split(".")
        .splice(-1)[0];
      let text = "";
      if (val === "doc" || val === "docx") {
        text = require("../images/doc.png");
      } else if (val === "xls" || val === "xlsx") {
        text = require("../images/xls.png");
      } else if (val === "pdf") {
        text = require("../images/pdf.png");
      } else if (val === "rar" || val === "zip") {
        text = require("../images/rar.png");
      }
      return text;
    },
    onChange() {
      this.$emit("input", this.fileUrls);
      this.$emit("change", this.fileUrls);
    },
    showMenu(idx) {
      if (this.disabled) {
        return false;
      }
      this.currentIdx = idx;
      this.$refs.popup.show();
    },
    hideMenu() {
      this.currentIdx = null;
      this.$refs.popup.close();
    },
    chooseImage() {
      this.hideMenu();
      const _count = 9 - this.appends.length;
      if (this.count === 1 && (this.currentIdx || this.currentIdx === 0)) {
        return;
      }
      uni.chooseImage({
        count: _count,
        success: res => {
          console.log("chooseImage", res);
          try {
            res.tempFiles.forEach(element => {
              if (element.size / 1024 / 1024 > 10) forEach.break = new Error();
            });
            this.upload(res.tempFiles);
            this.mask = true;
          } catch (error) {
            uni.showModal({
              title: "提示",
              showCancel: false,
              content: "请上传小于10MB的图片",
              success: () => {},
              confirmColor: this.settings.theme
            });
          }
        },
        fail: err => {
          console.log("debug log --> ", err);
          uni.showToast({
            title: "图片选择失败",
            icon: "none",
            duration: 2000
          });
        }
      });
    },
    chooseFile() {
      this.hideMenu();
      const _count = 9 - this.appends.length;
      if (this.count === 1 && (this.currentIdx || this.currentIdx === 0)) {
        return;
      }
      // #ifdef MP-WEIXIN
      wx.chooseMessageFile({
        type: "file",
        extenion: ["pdf", "doc", "docx"],
        count: _count,
        success: fileRes => {
          try {
            fileRes.tempFiles.forEach(element => {
              if (element.size / 1024 / 1024 > 10) forEach.break = new Error();
            });
            this.mask = true;
            this.upload(fileRes.tempFiles);
          } catch (error) {
            uni.showModal({
              title: "提示",
              showCancel: false,
              content: "请上传小于10MB的文件或图片",
              success: () => {},
              confirmColor: this.settings.theme
            });
          }
        },
        fail: fileErr => {
          uni.showToast({
            title: "文件选择失败",
            icon: "none",
            duration: 2000
          });
        }
      });
      // #endif
      // #ifdef H5
      // #endif
    },
    upload(file) {
      uni.showLoading({
        title:
          this.ingNum <= file.length
            ? `已上传${this.ingNum}/${file.length}`
            : "上传成功"
      });

      if (this.ingNum >= file.length) {
        uni.hideLoading();
        this.ingNum = 0;
        this.onChange();
        this.mask = false;
        return;
      }
      const formData = `${uni.getStorageSync("moduleCodeName")}${
        this.label
      }${this.appends.length + 1}`;
      console.log("formData", formData);
      // .${
      //         file[this.ingNum].path
      //           .split("/")
      //           .slice(-1)[0]
      //           .split(".")
      //           .splice(-1)[0]
      //       }
      const fileUrl = [
        {
          name: formData
        }
      ];
      console.log(
        "`${file[this.ingNum].path}?name=${formData}`",
        `${file[this.ingNum].path}?name=${formData}`
      );
      uploadFileFormData(`${file[this.ingNum].path}`, formData)
        .then(res => {
          console.log("res123", res);
          const url = res[0];
          const nameArr = url.split("/");
          const name = nameArr[nameArr.length - 1];
          const typeArr = name.split(".");
          const type = typeArr[typeArr.length - 1];

          const append = {
            url: url,
            name: name,
            type: imgTypes.includes(type) ? "img" : type
          };

          downloadFile(url)
            .then(dlres => {
              append["src"] = dlres.tempFilePath;
              if (this.currentIdx || this.currentIdx === 0) {
                const appendTemp = [].concat(this.appends);
                appendTemp[this.currentIdx] = append;
                this.appends = appendTemp;
              } else {
                this.appends.push(append);
              }
              this.ingNum++;
              this.hideMenu();
              this.upload(file);
            })
            .catch(dlerr => {
              console.log("debug log --> ", dlerr);
              append["src"] = null;
              if (this.currentIdx || this.currentIdx === 0) {
                const appendTemp = [].concat(this.appends);
                appendTemp[this.currentIdx] = append;
                this.appends = appendTemp;
              } else {
                this.appends.push(append);
              }

              this.onChange();
              this.hideMenu();
            });
        })
        .catch(err => {
          this.mask = false;
          console.log("debug log 12--> ", err);
          this.hideMenu();
          uni.showToast({
            title: err,
            icon: "none",
            duration: 2000
          });
        });
    },
    retrunName(url, index) {
      let num = index ? index : this.appends.length;
      return `${uni.getStorageSync("moduleCodeName")}${this.label}${num + 1}.${
        url
          .split("/")
          .slice(-1)[0]
          .split(".")
          .splice(-1)[0]
      }`;
    },
    async initAppendix(newV) {
      if (this.count > 1) {
        this.appends = [];
        for (let i = 0; i < this.count; i++) {
          this.appends.push(Object.assign({}, defaultAppend));
        }
        const appendTemp = [].concat(this.appends);
        if (newV.length > 0) {
          const urls = newV.split(",");
          for (let i = 0; i < urls.length; i++) {
            const nameArr = urls[i].split("/");
            const name = nameArr[nameArr.length - 1];
            const typeArr = name.split(".");
            const type = typeArr[typeArr.length - 1];
            if (appendTemp[i]) {
              let data = true;
              const url = await downloadFile(urls[i])
                .then(res => res.tempFilePath)
                .catch(() => {
                  data = false;
                  this.mask = false;
                });
              (appendTemp[i]["src"] = data
                ? src
                : require("../images/err.png")),
                (appendTemp[i]["url"] = urls[i]);
              appendTemp[i]["name"] = name;
              appendTemp[i]["type"] = imgTypes.includes(type) ? "img" : type;
            } else {
              break;
            }
          }
        }
        this.appends = appendTemp;
      } else {
        if (newV.length > 0) {
          const urls = newV.split(",");
          const tempAppends = [];
          urls.map(async (item, index) => {
            const nameArr = item.split("/");
            const name = this.retrunName(item, index); //nameArr[nameArr.length - 1];
            const typeArr = name.split(".");
            const type = typeArr[typeArr.length - 1];
            let data = true;
            let src = await downloadFile(item)
              .then(res => res.tempFilePath)
              .catch(() => {
                data = false;
                this.mask = false;
              });
            tempAppends.push({
              src: data ? src : require("../images/err.png"),
              url: item,
              name: name,
              type: imgTypes.includes(type) ? "img" : type
            });
          });
          this.appends = tempAppends;
        }
      }
    },
    confirm() {
      if (this.disabled) {
        return false;
      }
      if (this.count > 1) {
        const appendTemp = [].concat(this.appends);
        appendTemp[this.ingIndex] = Object.assign({}, defaultAppend);

        this.appends = appendTemp;
      } else {
        this.appends.splice(this.ingIndex, 1);
        this.onChange();
      }
    },
    // s
    removeAppendix(idx) {
      this.ingIndex = idx;
      this.show = true;
    }
  }
};
</script>
<style lang="scss" scoped>
.uploadingImg {
  display: flex;
  flex-wrap: wrap;
  min-height: 82px;
  padding: 8px;
  .img_warpBox {
    position: relative;
    width: 82px;
    border-radius: 4px;
    margin: 5px;
  }
  .fileBox {
    background: #ffffff;
    border-radius: 2px;
    border: 1px solid #ebebeb;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
  }
  .fileImgStyle {
    width: 60%;
    height: 60%;
  }
  .img_warp {
    position: relative;
    width: 82px;
    height: 82px;
    border-radius: 4px;
    margin: 5px;
    .img {
      width: 100%;
      height: 100%;
    }
    .det {
      position: absolute;
      right: 0;
      top: 0;
      width: 20px;
      height: 20px;
    }
  }
  .uploading_add {
    margin: 5px;
    width: 82px;
    height: 82px;
    border: 1px dashed #606266;
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .nameStyle {
    height: 22px;
    line-height: 12px;
    font-size: 12px;
    color: #929292;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
  }
}
</style>
